package com.cr.web.controller.api;

import com.cr.business.domain.TbUserBaseInfo;
import com.cr.business.domain.dto.app.LoginDto;
import com.cr.business.domain.dto.app.RegDto;
import com.cr.business.domain.dto.app.UpdatePasswordDto;
import com.cr.business.domain.dto.app.UpdatePhoneDto;
import com.cr.business.service.ITbUserBaseInfoService;
import com.cr.business.service.ITbUserEntityInfoService;
import com.cr.common.config.SystemConfig;
import com.cr.common.core.controller.BaseController;
import com.cr.common.core.domain.AjaxResult;
import com.cr.common.core.domain.model.AppLoginUser;
import com.cr.common.utils.SecurityUtils;
import com.cr.common.utils.StringUtils;
import com.cr.common.utils.file.FileUploadUtils;
import com.cr.common.utils.file.FileUtils;
import com.cr.common.utils.file.MimeTypeUtils;
import com.cr.framework.web.service.AppLoginService;
import com.cr.framework.web.service.AppTokenService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

import static com.cr.common.utils.SecurityUtils.getAppLoginUser;

/**
 * 账号相关接口
 *
 */
@RestController
@RequestMapping("api/account")
@Validated
public class AccountController extends BaseController {

    @Resource
    private ITbUserBaseInfoService tbUserBaseInfoService;

    @Resource
    private AppLoginService appLoginService;

    @Resource
    private AppTokenService appTokenService;

    @Resource
    private ITbUserEntityInfoService tbUserEntityInfoService;

    /**
     * 注册
     */
    @PostMapping("register")
    public AjaxResult register(@Valid RegDto dto){
        return toAjax(tbUserBaseInfoService.register(dto));
    }

    /**
     * 忘记密码
     */
    @PutMapping("forgetPassword")
    public AjaxResult forgetPassword(@Valid RegDto dto){
        return toAjax(tbUserBaseInfoService.forgetPassword(dto));
    }

    /**
     * 登录
     * @param info 登录信息
     */
    @PostMapping("/login")
    public AjaxResult login(@Valid LoginDto info)
    {
        return AjaxResult.success(appLoginService.appLogin(info.getPhone(), info.getPassword()));
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@NotNull(message = "文件不能为空！") @RequestParam(value = "file") MultipartFile file) throws Exception
    {
        if (file != null && !file.isEmpty()) {
            AppLoginUser appLoginUser = getAppLoginUser();
            String avatar = FileUploadUtils.upload(SystemConfig.getUserAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION, true);
            if (tbUserBaseInfoService.updateAvatar(appLoginUser.getUserId(), avatar)) {
                // 删除旧头像文件
                String oldAvatar = appLoginUser.getUser().getProfileUrl();
                if (StringUtils.isNotEmpty(oldAvatar)) {
                    FileUtils.deleteFile(SystemConfig.getProfile() + FileUtils.stripPrefix(oldAvatar));
                }
                // 更新缓存用户头像
                appLoginUser.getUser().setProfileUrl(avatar);
                appTokenService.setLoginUser(appLoginUser);

                return AjaxResult.successOneData("img", avatar);
            }
        }
        return error("上传图片异常，请联系管理员");
    }

    /**
     * 修改昵称
     */
    @PutMapping("/updateNickName")
    public AjaxResult updateNickName(@NotBlank(message = "昵称不能为空！") String nickName){
        int i = tbUserBaseInfoService.updateNickName(getAppLoginUser().getUserId(), nickName);
        if(i > 0) {
            AppLoginUser appLoginUser = getAppLoginUser();
            // 更新缓存用户昵称
            appLoginUser.getUser().setNickName(nickName);
            appTokenService.setLoginUser(appLoginUser);
        }
        return toAjax(i);
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public AjaxResult updatePassword(@Valid UpdatePasswordDto param){
        param.setUserId(getAppLoginUser().getUserId());
        int i = tbUserBaseInfoService.updatePassword(param);
        if(i > 0) {
            AppLoginUser appLoginUser = getAppLoginUser();
            // 更新缓存用户密码
            appLoginUser.getUser().setPassword(SecurityUtils.encryptPassword(param.getPassword()));
            appTokenService.setLoginUser(appLoginUser);
        }
        return toAjax(i);
    }

    /**
     * 修改手机号
     */
    @PutMapping("/updatePhone")
    public AjaxResult updatePhone(@Valid UpdatePhoneDto param){
        param.setUserId(getAppLoginUser().getUserId());
        int i = tbUserBaseInfoService.updatePhone(param);
        if(i > 0) {
            AppLoginUser appLoginUser = getAppLoginUser();
            // 更新缓存用户手机号
            appLoginUser.getUser().setPhone(param.getPhone());
            appTokenService.setLoginUser(appLoginUser);
        }
        return toAjax(i);
    }

    /**
     * 获取用户实体信息
     */
    @GetMapping("/getEntityInfo")
    public AjaxResult getEntityInfo(){
        return AjaxResult.success(tbUserEntityInfoService.appGetEntityInfo());
    }

    /**
     * 获取用户信息
     */
    @GetMapping("userInfo")
    public AjaxResult getUserInfo(){
        TbUserBaseInfo userInfo = tbUserBaseInfoService.getUserInfo(getAppLoginUser().getUserId());
        if(userInfo == null) {
            return error("用户信息不存在！");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("phone", userInfo.getPhone());
        data.put("nickName", userInfo.getNickName());
        data.put("profile", userInfo.getProfileUrl());
        data.put("authStatus", userInfo.getAuthStatus());
        return AjaxResult.success(data);
    }
}
